<template>
  <TForm v-model="formData" :columns="formColumns" @onFinish="onSubmit" @onReset="onReset" :formProps="formProps"></TForm>
</template>

<script lang="ts" setup>
import { TForm, TFormColumns, TFormProp } from '@twa/components'
import { ref } from 'vue'

const formData:any = ref({})

const formProps = ref<TFormProp>({
  labelWidth: '128px'
})
function onReset(){
  console.log('onReset', formData.value)
}
function onSubmit(){
  console.log('onSubmit', formData.value)
}

const checkDate1 = (_rule: any, _value: any, callback: any) => {
  if(!_value){
    callback(new Error('请选择开始日期'))
  }
  let startDate = new Date(formData.value.test9).getTime()
  let endDate = new Date(formData.value.test10).getTime()
  if(startDate > endDate) {
    callback(new Error('开始日期必须小于等于结束日期'))
  }
  callback()
}
const checkDate2 = (_rule: any, _value: any, callback: any) => {
  if(!_value){
    callback(new Error('请选择结束日期'))
  }
  let startDate = new Date(formData.value.test9).getTime()
  let endDate = new Date(formData.value.test10).getTime()
  if(startDate > endDate) {
    callback(new Error('结束日期必须大于等于开始日期'))
  }
  callback()
}

const formColumns = ref<TFormColumns[]>([
  { 
    label: '输入框', 
    prop: 'test1',
    valueType: 'input',
    formItemProps: {
      rules: [    
        { required: true, message: '请输入内容', trigger: 'blur' },
        { min: 1, max: 15, message: '内容长度最小为1，最大值为15', trigger: 'blur' },
      ]
    }
  },
  { 
    label: '下拉框', 
    prop: 'test4',
    valueType: 'select',
    valueEnum: [
      { label: '选项1', value: '1' },
      { label: '选项2', value: '2' },
      { label: '选项3', value: '3' },
    ],
    formItemProps: {
      rules: [   
        {
          required: true,
          message: '请选择下拉框',
          trigger: 'change',
        },
      ]
    }
  },
  { 
    label: '开始日期选择', 
    prop: 'test9',
    valueType: 'date',
    formItemProps: {
      rules: [{ required: true, validator: checkDate1, trigger: 'change' }]
    }
  },
  { 
    label: '结束日期选择', 
    prop: 'test10',
    valueType: 'date',
    formItemProps: {
      rules: [{ required: true, validator: checkDate2, trigger: 'change' }]
    }
  },
])
</script>